package club.dataresources.controller;

import club.dataresources.common.R;
import club.dataresources.entity.Customer;
import club.dataresources.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author
 * @create 2018-10-30 21:37
 **/
@RequestMapping(value = "/")
@Controller
public class LoginController {

    @Autowired
    private LoginService loginService;

    /**
     * 前台用户注册
     **/
    @RequestMapping(value = "/register", method = {RequestMethod.POST, RequestMethod.GET})
    public @ResponseBody
    R register(HttpServletRequest request, HttpServletResponse response, @RequestBody Customer customer) {
        System.out.println("================前台用户注册================");
        try {
            Customer cu = loginService.register(customer);
            if(cu==null){
                //重复
                return R.error(500,"您使用的用户名已经存在");
            }else{
                loginService.login(cu);
                return R.ok().put("data",cu).put("code",200).put("msg","注册成功，即将登录");
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.error().put("code",500).put("msg","后台服务器异常");
        }
    }

    /**
     * 前台用户登录
     **/
    @RequestMapping(value = "/login", method = {RequestMethod.POST, RequestMethod.GET})
    public @ResponseBody
    R login(HttpServletRequest request, HttpServletResponse response,@RequestBody Customer customer) {
        System.out.println("================前台用户登录================");
        try{
            Customer cu = loginService.login(customer);
            if(cu!=null){
                //密码一致
                if(customer.getPassword().equals(cu.getPassword())){
                    //登录通过,将customer对象存进session
                    System.out.println("====="+cu.getName()+"=====标记customerLoginFlag 前台登录通过=====");
                    request.getSession().setAttribute("customerLoginFlag",cu);
                    return R.error().put("data",cu).put("code",200).put("msg","登录成功");
                }else{
                    cu.setPassword("***");
                    return R.error().put("data",cu).put("code",500).put("msg","您输入的密码错误");
                }
            }else{
                return R.error().put("data",cu).put("code",500).put("msg","该用户尚未注册");
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.error().put("data",null).put("code",500).put("msg","后台服务器异常");
        }
    }
}
